package com.starblink.imgsearch.camera

import com.starblink.rocketreserver.FetchImgSearchAuthTokenQuery
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.logging.HttpLoggingInterceptor
import java.io.File
import java.io.IOException

object OssUploader {

    private const val TAG = "OssUploader"

    private val client = OkHttpClient.Builder()
        .addInterceptor(HttpLoggingInterceptor()
            .apply {
                setLevel(HttpLoggingInterceptor.Level.BODY)
            }).build()

    suspend fun upload(
        file: File,
        data: FetchImgSearchAuthTokenQuery.FetchImgSearchAuthToken
    ): Boolean {
        return withContext(Dispatchers.IO) {
            val url = data.picUrl.replace(data.objectKey, "")
            val call = client.newCall(
                Request.Builder()
                    .url(url)
                    .post(
                        MultipartBody.Builder()
                            .addFormDataPart("key", data.objectKey)
                            .addFormDataPart("success_action_status", "200")
                            .addFormDataPart("OSSAccessKeyId", data.stsAccessKeyId)
                            .addFormDataPart("policy", data.encodedPolicy)
                            .addFormDataPart("Signature", data.signature)
                            .addFormDataPart("Content-Type", "image/jpeg")
                            .addFormDataPart("x-oss-content-type", "image/jpeg")
                            .addFormDataPart("file", file.name, file.asRequestBody())
                            .setType(MultipartBody.FORM)
                            .build()
                    ).build()
            )
            try {
                call.execute().isSuccessful
            } catch (e: IOException) {
                e.printStackTrace()
                false
            } catch (e: Exception) {
                e.printStackTrace()
                false
            }
        }


    }

}